package com.lichongbing.lyoggl.apple;
import com.lichongbing.lyoggl.config.ConstConfig;
import com.lichongbing.lyoggl.service.LyogglUsersService;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;

/**
 * @author lichongbing
 * @version 1.0.0
 * @createdate 2022/9/16 09:24
 * @description: TODO
 */
@Service
public class ApnsServe {
    private static String SANDBOX_SERVER = "api.sandbox.push.apple.com:443";
    private static String PRODUCT_SERVER = "api.push.apple.com:443";
    private static String APPID = "com.lichongbing.timing";
    @Autowired
    private LyogglUsersService lyogglUsersService;

    public static String generateAPNsauthorizationToken() throws Exception {
        Map<String, Object> header = new HashMap<>();
        //P8文件下载得到的Key ID
        header.put("kid", "9TPD8SS3C6");
        //SHA256
        header.put("alg", SignatureAlgorithm.ES256.getValue());
        Map<String, Object> claims = new HashMap<>();
        long now = System.currentTimeMillis() / 1000;
        claims.put("iss", ConstConfig.TEAM_ID);
        claims.put("iat", now);
        // 最长半年，单位秒
        claims.put("exp", now + 648000);
        claims.put("aud", ConstConfig.REVOKE_AUD);
        claims.put("sub", ConstConfig.CLIENT_ID);
        //P8文件下载得到的Key Value
        String  privatekeyValue = "MIGTAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBHkwdwIBAQQgrxS0HVpmGSD4y7DdEjIr5jxz6yhsSd79GKm2QFhupy6gCgYIKoZIzj0DAQehRANCAASEkeSiq4TeLf3RkK0NhvSYR+7uq19qlgJDsMgYGjgdnQ5dBBj/vz/w9bE2MxxFu+OvHNPqttesTlttsOusA+m5";
        PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(Base64.decodeBase64(privatekeyValue));
        KeyFactory keyFactory = KeyFactory.getInstance("EC");
        PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
        return Jwts.builder().setHeader(header).setClaims(claims).signWith(SignatureAlgorithm.ES256, privateKey).compact();
    }

    public int  updateLockScreenandDynamicIsland(String userid,String payload){
        String pushToken = lyogglUsersService.getPushToken(userid);
        try {
            HttpRequest request = HttpRequest.newBuilder()
                    // deviceToken 从手机上获取到的设备 token
                    .uri(URI.create("https://" +  PRODUCT_SERVER +"/3/device/" + pushToken))
                    // 发送的消息内容
                    .POST(HttpRequest.BodyPublishers.ofString(payload))
                    // 请苹果接口的令牌，通过 JWT 生成，有时间有过期（好像是一个小时过期，所以不要去缓存它，每次请求时去重新生成一个就好）
                    .setHeader("authorization", "bearer "+ generateAPNsauthorizationToken())
                    // 消息的提示方式，liveactivity 灵动岛和锁屏组件通知更新
                    .setHeader("apns-push-type", "liveactivity")
                    //  APPID，和证书一致
                    .setHeader("apns-topic", APPID+".push-type.liveactivity")
                    .build();
            HttpClient client = HttpClient.newBuilder().build();
            HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString());
            // 返回状态码，如果是 200 则表示发送成功
            Integer statuCode = response.statusCode();
            if (statuCode == null || statuCode.intValue() != 200) {
                // 如果返回的状态码不是200，则发送失败，response.body() 是错误的原因
                System.out.println(response.body());
                return 400;
            }else{
                return 200;
            }
        }catch (Exception  e){
            System.out.println(e.getMessage());
            return 400;
        }





    }
}
